using System;
using System.Net;
using System.Net.Mail;

namespace ScrewTurn.Wiki
{
    /// <summary>
    /// Sends Emails.
    /// </summary>
    public static class EmailSender
    {
        /// <summary>
        /// Sends an Email.
        /// </summary>
        /// <param name="recipient">The Recipient.</param>
        /// <param name="sender">The Sender.</param>
        /// <param name="subject">The Subject.</param>
        /// <param name="body">The Message body.</param>
        /// <param name="html">True if the body is HTML.</param>
        public static void Send(string recipient, string sender, string subject, string body, bool html)
        {
            var message = new MailMessage(sender, recipient, subject, body);
            message.IsBodyHtml = html;
            TrySendMessage(message);
        }

        /// <summary>
        /// Sends a Mass Email, using BCC.
        /// </summary>
        /// <param name="recipients">The Recipents.</param>
        /// <param name="sender">The Sender.</param>
        /// <param name="subject">The Subject.</param>
        /// <param name="body">The Body.</param>
        /// <param name="html">True if the body is HTML.</param>
        public static void SendMassEmail(string[] recipients, string sender, string subject, string body, bool html)
        {
            var message = new MailMessage(new MailAddress(sender), new MailAddress(sender));
            message.Subject = subject;
            message.Body = body;
            for (int i = 0; i < recipients.Length; i++)
            {
                message.Bcc.Add(new MailAddress(recipients[i]));
            }
            message.IsBodyHtml = html;
            TrySendMessage(message);
        }

        private static void TrySendMessage(MailMessage message)
        {
            try
            {
                GenerateSmtpClient().Send(message);
            }
            catch (Exception ex)
            {
                if (ex is SmtpException)
                {
                    Log.LogEntry("Unable to send Email: " + ex.Message, EntryType.Error, "SYSTEM");
                }
                else Log.LogEntry(ex.ToString(), EntryType.Error, "SYSTEM");
            }
        }

        private static SmtpClient GenerateSmtpClient()
        {
            var client = new SmtpClient(Settings.SmtpServer);
            if (Settings.SmtpUsername.Length > 0)
            {
                client.Credentials = new NetworkCredential(Settings.SmtpUsername, Settings.SmtpPassword);
            }
            client.EnableSsl = Settings.SmtpSsl;
            if (Settings.SmtpPort != -1) client.Port = Settings.SmtpPort;
            else if (Settings.SmtpSsl) client.Port = 465;
            return client;
        }
    }
}